package server

import (
	"fmt"
	runcomm "gitee.com/gitee-go/runner-core/comm"
	"gitee.com/gitee-go/runner-core/runner"
	dag2 "gitee.com/gitee-go/server/comm/yml/dag"
	"gitee.com/gitee-go/server/engine"
	"gitee.com/gitee-go/server/routehb"
	hbtp "github.com/mgr9525/HyperByte-Transfer-Protocol"
	"github.com/sirupsen/logrus"
	"path/filepath"
	"runtime/debug"

	"gitee.com/gitee-go/core"
	"gitee.com/gitee-go/server/comm"
)

// DaemonServer start server
func DaemonServer() (rterr error) {
	defer func() {
		if err := recover(); err != nil {
			core.LogPnc.Errorf("DaemonServer start:%+v", err)
			core.LogPnc.Errorf("%s", string(debug.Stack()))
			rterr = fmt.Errorf("recover:%v", rterr)
		}
	}()
	if err := initDB(comm.MainCfg.DataConf); err != nil {
		core.Log.Errorf("InitDB err: %v", err)
		return err
	}
	if err := initCache(); err != nil {
		core.Log.Errorf("InitCache err: %v", err)
		return err
	}
	defer comm.BCache.Close()
	dag2.InitDAG()
	if err := engine.Start(); err != nil {
		core.Log.Errorf("engine.Start() err: %v", err)
		return err
	}
	core.Log.Info("Init ok")
	regApi()
	go runHbtp()
	go runRunner()
	engine.Wait()
	return nil
}

// 启动grpc服务
func runHbtp() {
	eng := hbtp.NewEngine(engine.Mgr().Ctx)
	eng.RegFun(1, hbtp.RPCFunHandle(&routehb.ClientRPC{})) //runner client控制
	eng.RegFun(2, hbtp.RPCFunHandle(&routehb.RunnerRPC{})) //runner注册成功后的所有操作
	//eng.RegFun(3, hbtp.RPCFunHandle(&routehb.SysRPC{}))
	if err := eng.Run(":" + comm.MainCfg.RunnerConf.Port); err != nil {
		logrus.Error("StartConnEngine run err:" + err.Error())
		engine.Stop()
	}
}

/*func BackgroundServer(ctx context.Context) {
	srv := NewWeb()
	srv.Start(ctx, ":8091")
}*/

// 启动内置 runner
func runRunner() {
	defer func() {
		if err := recover(); err != nil {
			core.LogPnc.Errorf("runRunner:%+v", err)
			core.LogPnc.Errorf("%s", string(debug.Stack()))
		}
	}()

	if comm.MainCfg.RunnerConf == nil || !comm.MainCfg.RunnerConf.MainRunner {
		return
	}
	cf := &runcomm.ExecerConfig{
		Name:     "mainRunner",
		ServAddr: "localhost",
		Plugin:   []string{"shell@sh", "shell@bash"},
	}
	if comm.MainCfg.RunnerConf != nil {
		cf.ServAddr = fmt.Sprintf("127.0.0.1:%s", comm.MainCfg.RunnerConf.Port)
		cf.Secret = comm.MainCfg.RunnerConf.Secret
		//cf.Workspace=comm.MainCfg.MainRunner.Workspace
		//cf.Limit=comm.MainCfg.MainRunner.Limit
	}
	if cf.Workspace == "" {
		cf.Workspace = filepath.Join(comm.WorkPath, "mainrunner")
	}
	core.Log.Debugf("start mainRunner addr:%s,workpth:%s", cf.ServAddr, cf.Workspace)
	err := runner.StartManager(cf)
	if err != nil {
		logrus.Error("runRunner err:" + err.Error())
	}
}
